import { Component, OnDestroy, OnInit } from '@angular/core';
import { TodoFilter, TodoService } from '../todo.service';
import { Todo } from '../todo.model';
import { Subject, Subscription } from 'rxjs';
import { ActivatedRoute } from '@angular/router';
import { map, takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-todo',
  templateUrl: './todo.component.html',
  styleUrls: ['./todo.component.css']
})
export class TodoComponent implements OnInit, OnDestroy {

  todos: Todo[];
  todoCount: number;

  filteredTodos: Todo[];

  uncompletedCount = 0;
  completedCount = 0;

  private readonly unsubscribe$: Subject<void> = new Subject<void>();

  constructor(
    private readonly route: ActivatedRoute,
    private readonly todoService: TodoService
  ) { }

  ngOnInit(): void {
    this.route.paramMap
      .pipe(
        map(params => params.get('filter'))
      )
      .subscribe((filter: TodoFilter) => {
        this.filteredTodos = this.filteredTodos = this.todoService.filter(filter);
      });

    this.todoService.todos$
      .pipe(
        takeUntil(this.unsubscribe$)
      )
      .subscribe(todos => {
        this.todos = todos;
        this.todoCount = this.todos.length;
        this.filteredTodos = this.todoService.filter(this.route.snapshot.paramMap.get('filter') as TodoFilter);

        const completedTodos = this.todos.filter(it => it.completed);
        this.completedCount = completedTodos.length;
        this.uncompletedCount = this.todos.length - completedTodos.length;

        console.log(JSON.stringify(this.todos));
      });
    // this.todoService.count$
    //   .pipe(
    //     takeUntil(this.unsubscribe$)
    //   )
    //   .subscribe(count => {
    //     this.todoCount = count;
    //   });
  }

  ngOnDestroy(): void {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }

}
